package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.api.WechatApi;
import com.vast.admin.entity.ApplyMsgUser;
import com.vast.admin.entity.Customer;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.admin.entity.enums.OperatorEum;
import com.vast.admin.entity.enums.QueryOrderEnum;
import com.vast.admin.mapper.ApplyMsgUserMapper;
import com.vast.admin.utils.QueryBuilder;
import com.vast.admin.utils.TableFieldColumnsUtils;
import com.vast.common.utils.StringUtils;
import com.vast.system.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ApplyMsgUserService extends ServiceImpl<ApplyMsgUserMapper, ApplyMsgUser> {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private WechatApi wechatApi;

    public IPage<ApplyMsgUser> queryList(Page<ApplyMsgUser> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
        QueryWrapper<ApplyMsgUser> queryWrapper = new QueryWrapper<>();
        Map<String, String> fieldColumns = TableFieldColumnsUtils.getInstance().getFieldTableColumns(ApplyMsgUser.class);
        if (listMode) {
            // size 小于 0 不在查询 total 及分页，自动调整为列表模式。
            // 注意！！这个地方自己控制好！！
            page.setSize(-1);
        }
        if (!StringUtils.isEmpty(queryItems)) {
            List<QueryBuilder> queryBuilders = new ArrayList<>();
            String[] queryItemArr = queryItems.split(";");
            if(queryItemArr.length > 0){
                for (String queryItemStr : queryItemArr) {
                    String[] itemArr = queryItemStr.split(",");
                    if(itemArr.length == 3){
                        String as = itemArr[1];
                        String params = itemArr[2];
                        if(!StringUtils.isEmpty(params)){
                            queryBuilders.add(new QueryBuilder(itemArr[0], OperatorEum.valueOf(as),itemArr[2]));
                        }
                    }
                }
            }

            for (QueryBuilder queryBuilder : queryBuilders) {
                //查询字段
                String field = queryBuilder.getField();
                //查询参数值
                String params = queryBuilder.getParams();
                if (fieldColumns.containsKey(field) && !StringUtils.isEmpty(params)) {
                    //表属性
                    String tableColumn = fieldColumns.get(field);
                    if (queryBuilder.getAs() == OperatorEum.EQ) {
                        queryWrapper.eq(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LIKE){
                        queryWrapper.like(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LIKELEFT){
                        queryWrapper.likeLeft(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LIKERIGHT){
                        queryWrapper.likeRight(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.GE){
                        queryWrapper.ge(tableColumn, params);
                    }else if(queryBuilder.getAs() == OperatorEum.LE){
                        queryWrapper.le(tableColumn, params);
                    }
                }
            }
        }
        if (!StringUtils.isEmpty(orderField)) {
            String[] orderByColumns = orderField.split(",");
            String queryOrderByColumns = "";
            if (orderByColumns.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (String orderByColumn : orderByColumns) {
                    if (fieldColumns.containsKey(orderByColumn)) {
                        sb.append(fieldColumns.get(orderByColumn)).append(",");
                    }
                }
                if (sb.length() > 0) {
                    queryOrderByColumns = sb.deleteCharAt(sb.length() - 1).toString();
                }
            }
            if (!StringUtils.isEmpty(queryOrderByColumns)) {
                if(order == null){
                    order = QueryOrderEnum.ASC;
                }
                if (order == QueryOrderEnum.ASC) {
                    queryWrapper.orderByAsc(queryOrderByColumns);
                } else if (order == QueryOrderEnum.DESC) {
                    queryWrapper.orderByDesc(queryOrderByColumns);
                }
            }

        }

        IPage<ApplyMsgUser> result = baseMapper.selectPage(page, queryWrapper);


        return result;
    }

    @Transactional
    public boolean delete(SysUser manager, Long[] ids) {
        return super.removeByIds(Arrays.asList(ids));
    }

    @Transactional
    public void add(SysUser manager, Long[] customerIds) {
        Date date = new Date();
        for (Long customerId : customerIds) {
            if (isExist(customerId)) {
                continue;
            }
            Customer customer = customerService.getById(customerId);
            if (customer == null) {
                throw new BusinessException("添加的用户不存在或已被删除");
            }
            ApplyMsgUser applyMsgUser = new ApplyMsgUser();
            applyMsgUser.setCustomerId(customer.getId());
            applyMsgUser.setName(customer.getName());
            applyMsgUser.setMobile(customer.getMobile());
            applyMsgUser.setIdentity(customer.getIdentity());
            applyMsgUser.setWxId(customer.getWxId());
            applyMsgUser.setCreateBy(manager.getUserId());
            applyMsgUser.setCreateTime(date);
            super.save(applyMsgUser);
        }
    }

    private boolean isExist(Long customerId) {
        QueryWrapper<ApplyMsgUser> applyMsgUserQueryWrapper = new QueryWrapper<>();
        applyMsgUserQueryWrapper.eq(ApplyMsgUser.COL_CUSTOMER_ID, customerId);
        return super.count(applyMsgUserQueryWrapper) > 0;
    }

    /**
     * 推送消息
     * @param name
     * @param mobile
     * @param companyName
     */
    public void pushMsg(String name, String mobile, String companyName) {
        for (ApplyMsgUser applyMsgUser : super.list()) {
            wechatApi.pushAppApplyMsg(applyMsgUser.getWxId(), name, mobile, companyName);
        }
    }
}
